import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {

	private Socket socket;
	private AbstractHttpWorker worker;
	
    public WorkerThread(Socket clientSocket) {
		this.socket = clientSocket;
	}

	public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        
        // create pool of worker threads
        ExecutorService pool = Executors.newFixedThreadPool(workers);
        
        // create server socket
        final ServerSocket serverSocket = new ServerSocket(port);
        
        // accept connections
        while (true) {
        	Socket clientSocket = serverSocket.accept();
        	clientSocket.setSoTimeout(timeout);
        	pool.execute(new WorkerThread(clientSocket));
        }
    }

    public void run() {
        worker = new Worker();
    	try {
			worker.handleRequest(socket);
		} catch (IOException e1) {
			e1.printStackTrace();
			try {
				socket.close();
			} catch (IOException e2) {
                e2.printStackTrace();
            }
		}
    }
}